/**
* Module dependencies.
*/

var mongoose = require('mongoose'), 
Schema = mongoose.Schema,
crypto = require('crypto');

var UserSchema = Schema({
	username : { type: String, default: '' },
	hashed_password : { type: String, default: '' },
	salt: { type: String, default: '' },
	
	curChar : { type: Number, default: 0 },
	banned : { type: Boolean, default: false },
	isAdmin : { type: Boolean, default: false },
	isOnline : { type: Boolean, default: true },
	lastOnline : { type: Date, default: Date.now },
	socketID : String,
	
	chars: 
	[{ 
		charID : mongoose.Schema.ObjectId
	}]		
});

UserSchema
.virtual('password')
.set(function(password) {
	this._password = password
	this.salt = this.makeSalt()
	this.hashed_password = this.encryptPassword(password)
})
.get(function() { return this._password })

  
UserSchema.path('username').validate(function (username) {
	return username.length
}, 'Username cannot be blank')

UserSchema.path('hashed_password').validate(function (hashed_password) {
	return hashed_password.length
}, 'Password cannot be blank')
  
UserSchema.methods = {
	authenticate: function (plainText) {
		return this.encryptPassword(plainText) === this.hashed_password
	},

	makeSalt: function () {
		return Math.round((new Date().valueOf() * Math.random())) + ''
	},

	encryptPassword: function (password) {
		if (!password) return ''
		var encrypred
		try {
			encrypred = crypto.createHmac('sha1', this.salt).update(password).digest('hex')
			return encrypred
		} catch (err) {
			return ''
		}
	}
}

mongoose.model('User', UserSchema)